/* 公共request 方法 */
// const server= 'https://pcw.ehmall.com.cn';//正式域名api
//const server= 'https://aiteshop.com.cn';//测试域名api
//const server= 'https://ehmall.eachone.com';//内部测试域名api
const server = 'https://uriwin.com'; //正式域名api
// const server = 'https://pcw.ehmall.com.cn  ehmall.aiteds.com';//正式域名api
const msdjs = require('./md5.js');

function getQueryString(name, url, ture) { //参数截取
	if (ture) {
		var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
	} else {
		var reg = new RegExp('(^|/?)' + name + '=([^&]*)(&|$)', 'i');
	}

	var r = url.substr(1).match(reg);
	if (r != null) {
		return unescape(r[2]);
	}
	return null;
}


const requestUrl = ({
	that,
	url,
	data,
	success,
	ToLogin = true,
	isFirst = false,
	method = "GET"
}) => {
	let shopping_select = JSON.stringify(uni.getStorageSync("shopping_select"))
	var header = {
		'content-type': 'application/x-www-form-urlencoded'
	}
	//获取当前时间戳
	let timestamp = Date.parse(new Date());
	timestamp = timestamp / 1000;

	data.api_time = timestamp;
	// let unionId = uni.getStorageSync("unionId")?uni.getStorageSync("unionId") : "";
	if (data.goods_link) {
		data.goods_link = data.goods_link.replace(/\=/, "%3D")
		data.goods_link = data.goods_link.replace(/\?/g, "%3F")
		data.goods_link = data.goods_link.replace(/\#/g, "%23")
	}
	data.op = getQueryString("op", url, true) || "";
	data.act = getQueryString("act", url, false) || "";
	data.comefrom = "WAP"
	let APIKEY = "AWAP78851ERFG85"
	// #ifdef APP-PLUS
	uni.getSystemInfo({
		success: (res) => {
			if (res.platform == "android") {
				data.comefrom = "ANDROID";
			} else {
				data.comefrom = "IOS";
			}
		}
	})
	APIKEY = "ANHK78451ERFG17"
	// #endif
	// #ifdef H5
	let ua = window.navigator.userAgent.toLowerCase();
	if (ua.match(/MicroMessenger/i) == 'micromessenger') {
		data.comefrom = "WECHAT";
		APIKEY = "AWECHAT788NDG85"
	} else {
		data.comefrom = "WAP";
		APIKEY = "AWAP78851ERFG85"
	}
	// #endif
	// #ifdef MP-WEIXIN
	data.comefrom = "APPLET";
	APIKEY = "LET78451EHMG63"
	// #endif

	// if(data.op!="goods_list"&&data.act!="goods"){
	data.key = uni.getStorageSync("key") || "";
	// }

	//已经登录的，投放一次，让他绑定 ，没登录的让他登录，登录接口登录 切换投放一下
	let share_phyid = uni.getStorageSync("share_phyid")
	if (share_phyid) {
		if (data.key.length) {
			//投放一次 清除
			uni.removeStorage({ key: "share_phyid" })
		}
		data.share_phyid = share_phyid
	}
	console.log("gogo " + share_phyid)


	// 接口签名 
	let api_signMd5 = ksort(data);

	let forinstring = "";

	for (let key in api_signMd5) {
		if (key != "file") {
			forinstring += "&" + key + "=" + encodeURI(api_signMd5[key])
		}
	}



	api_signMd5 = forinstring.replace("&", "") + APIKEY;
	api_signMd5 = api_signMd5.replace(/,/g, "%2C")
	api_signMd5 = api_signMd5.replace(/@/g, "%40")
	api_signMd5 = api_signMd5.replace(/#/g, "%23")
	api_signMd5 = api_signMd5.replace(/\//g, "%2F")
	api_signMd5 = api_signMd5.replace(/:/g, "%3A")
	api_signMd5 = api_signMd5.replace(/\+/g, "%2B")
	api_signMd5 = api_signMd5.replace(/\*/g, "%2A")
	api_signMd5 = api_signMd5.replace(/\(/g, "%28")
	api_signMd5 = api_signMd5.replace(/\)/g, "%29")

	// data.api_sign = msdjs.hexMD5(api_signMd5);
	// console.log(api_signMd5)
	data.api_sign = msdjs.hexMD5(api_signMd5).toUpperCase()
	data.api_sign = data.api_sign.toLocaleLowerCase()
	// console.log(data,api_signMd5);
	console.log('请求数据', data)
	return new Promise(function (resolve, reject) {
		uni.request({
			url: server + url,
			method: method,
			data: data,
			header: header,
			success: (res) => {
				//token已失效，您已在其他客户端登录
				let href = ""
				// #ifdef H5
				href = encodeURIComponent(window.location.href)
				// #endif
				console.log(res.data)
				if ((res.data.error_code == 403 && (data.act != "member_security" && data.op != "member")) || (res.data.message == '查询不到Token数据')) {
					uni.navigateTo({
						url: '/mainA/login/login?href=' + href
					})
					uni.removeStorageSync("key");
					uni.removeStorageSync("api_member_name")
					uni.removeStorageSync("api_member_id")
					uni.removeStorageSync("openid")
					return false
				} else if (res.error_code == '1840002') {
					resolve(res.data)
				} else {
					if (isFirst) {
						resolve(res.data)
					} else {
						if (res.data.login == "0") {

						} else {
							console.log(res.data)
							if (res.data.message == 'token已失效，您已在其他客户端登录') {
								uni.reLaunch({
									url: '/mainA/login/login?href=' + href
								})
								uni.removeStorageSync("key");
								uni.removeStorageSync("api_member_name")
								uni.removeStorageSync("api_member_id")
								uni.removeStorageSync("openid")
								return false
							}
							// 需要返回
							resolve(res.data)
						}
					}
				}

			},
			fail: function (res) {
				//console.log('请求错误', res)
				reject(res.data)
			},

			complete: function (res) {
				let href = ""
				// #ifdef H5
				href = window.location.href
				// #endif
				if (res.data.error_code == '401' && (data.act != "member_security" && data.op !=
					"member")) {
					if (ToLogin) {
						uni.showToast({
							title: "您暂未登录",
							icon: "none",
							success() {
								setTimeout(() => {
									uni.navigateTo({
										url: '/mainA/login/login?href=' + href
									})
									uni.removeStorageSync("key");
									uni.removeStorageSync("api_member_name")
									uni.removeStorageSync("api_member_id")
									uni.removeStorageSync("openid")
								}, 1000)
							}
						})
					}
				}

			}
		});
	})
		.catch((res) => { })
}

/* 公共showTotast  loading 方法 */
module.exports = {
	request: requestUrl,
	server
};

function ksort(o) { //参数排序
	let sorted = {},
		keys = Object.keys(o);
	keys.sort();
	keys.forEach((key) => {
		sorted[key] = o[key];
	})
	return sorted;
}